/**
 * Created by d8q8 on 2015/1/19.
 * @class JSSDK
 * @constructor
 **/
declare function getJSUrl();
declare function showMenu();
declare function onBridgeReady(_timestamp:string,_nonceStr:string,_package:string,_signType:string,_paySign:string,_appId:string);
interface SignPackage {
    appId: string;
    nonceStr: string;
    timestamp: number;
    signature: string;
    url: string;
}

class JSSDK extends egret.DisplayObjectContainer {
    public CLASS_NAME: string = "JSSDK";    
    private signPackage: SignPackage;
    private url: string;

    private title: string;
    private desc: string;
    public link: string;
    public imgUrl: string;
    public shareComplete: any;
    public thisObj: any;
    //private time: number = 25;
   
    public constructor() {
        super();
        this.addEventListener(egret.Event.ADDED_TO_STAGE,this.onAddToStage,this);
    }

    protected onAddToStage(e: egret.Event) {
        this.removeEventListener(egret.Event.ADDED_TO_STAGE,this.onAddToStage,this);
        //初始化
        this.init();
    }

    private _dataFX:any;

    public setTitle(title: string,desc: string,toLink:string,iconName:string="icon1"): void {
       // console.log("\n分享参数:"+title+"\n"+desc);
        this.title = title;
        this.desc = desc;
        this.imgUrl = StageData.JSSDKStr+"/pingjiangMj/"+iconName+".png";//GameData.linkStr + "/views/ownpage.jpg";
        this.link = toLink;
       // alert("分享链接："+this.link); 
       this.getSignPackage();
    }
    
    /**
     * 初始化
     **/
    private initOk:boolean = false;
    public init() {   
        //初始化分享内容
        this.title = "帅帅游戏";
        this.desc = '好友斗牛，“抢庄模式”“牛牛坐庄”“霸王庄”手牌可见-3、4、5张，人数不限、多种玩法，点击进入决战到天亮....';        
        this.link = StageData.linkStr+"/login/weiXin/"+GameData.areaCode;
        
        this.imgUrl = StageData.JSSDKStr+"/lftgame/icon1.png";
       // this.url = "http://xiaoya.excellent-media.com/share?url=" + encodeURIComponent(location.href.split("#")[0]);
        //获取签名
        this.getSignPackage();
    }

    /**
     * 获取签名分享
     */
    private getSignPackage(){
        var ls:string = getJSUrl();
        var thisPageUrl:string = StageData.linkStr+"/weixin/"+GameData.areaCode+"?type=10011"+"roomNo="+GameData.roomNo;
        var sdf:string = '{"source":{"signUrl":"'+encodeURIComponent(getJSUrl())+'"},"type":1004,"token":"'+GameData.token+'"}';
		this.once("upload",this.serverComplete,this);
		this.upload(StageData.HTTP_URL,new egret.URLVariables("?JSON="+sdf));  
    }
         
    private serverComplete(e:egret.Event){
           //alert("收到分享数据:"+this.urlJson.source);
           if(this.urlJson.source){
               if(this.urlJson.source.shareLink){
                   this.link = this.urlJson.source.shareLink+"?roomNo="+GameData.roomNo+"&type=10011";
               }
               this._dataFX = {_appid:this.urlJson.source.shareAppId,_timestamp:this.urlJson.source.shareTimestamp,_nonceStr:this.urlJson.source.shareNonceStr,_signature:this.urlJson.source.shareSignature};
               //基本配置
               this.getWeiXinConfig();
            var self = this;
            var funcSucceed = () => {
                //下面可以加更多接口,可自行扩展
                // egret.log("接jssdk成功！!!");
                self.getWeiXinShareTimeline();//分享朋友圈
                self.getWeiXinShareAppMessage();//分享朋友
                self.getWeiXinShareQQ();//分享QQ
                self.getWeiXinShareWeiBo();//分享到腾讯微博
                self.getLocation()

                StageData.soundObj.soundSinglePlay("click");

                showMenu();//显示微信菜单
                StageData.FXOBJ.dispatchEventWith("fxComplete");//授权成功
                //if(StageData.JSSDKSound == false){
                   //alert("授权成功JSSDKSound："+StageData.JSSDKSound);
                   //StageData.soundObj.soundSinglePlay("getCard",this.soundOver);
                   //StageData.MainObj.JSSDKPlaySOUND(); //播放背景音乐
                //}
            }
            var funcError = (res) => {
               /* if(this.timer){
                    egret.clearTimeout(this.timer);
                }
                this.timer = egret.setTimeout(()=>{
                    egret.clearTimeout(this.timer);*/
                    self.getSignPackage();
               // },this,200);
            }

            wx.ready(funcSucceed);
            wx.error(funcError);
           // GameData.MainObj.setBgMusic();//本地可以暂时取消，正式打包需要开启
           }
    }
    private timer;
    public soundOver(){
        StageData.JSSDKSound  = true;
    }

    /*//声音加载完成后执行声音播放
    public playInitSound(){
        //console.log("JSSDK_Sound");
        let thisPageUrl:string = StageData.linkStr+"/weixin/"+GameData.areaCode+"?type=10003"+"roomNo="+GameData.roomNo;
        var sdf:string = '{"source":{"signUrl":"'+encodeURIComponent(getJSUrl())+'"},"type":1004,"token":"'+GameData.token+'"}';
		this.once("upload",this.SoundserverComplete,this);
		this.upload(StageData.HTTP_URL,new egret.URLVariables("?JSON="+sdf)); 
            
    }
     private SoundserverComplete(e:egret.Event){
           //alert("收到分享数据:"+this.urlJson.source);
           if(this.urlJson.source){
               //console.log("微信签名："+JSON.stringify(this.urlJson.source));
               if(this.urlJson.source.shareLink){
                   this.link = this.urlJson.source.shareLink+"?roomNo="+GameData.roomNo+"&type=10003";
               }
               this._dataFX = {_appid:this.urlJson.source.shareAppId,_timestamp:this.urlJson.source.shareTimestamp,_nonceStr:this.urlJson.source.shareNonceStr,_signature:this.urlJson.source.shareSignature};
               //基本配置
               this.getWeiXinConfig();
            var self = this;
            var funcSucceed = () => {
                //下面可以加更多接口,可自行扩展
                // egret.log("接jssdk成功！!!");
                self.getWeiXinShareTimeline();//分享朋友圈
                self.getWeiXinShareAppMessage();//分享朋友
                self.getWeiXinShareQQ();//分享QQ
                self.getWeiXinShareWeiBo();//分享到腾讯微博

                   // alert("授权成功");
                   StageData.soundObj.startSound("s");
                    //GameData.MainObj.JSSDKPlaySOUND(); //播放背景音乐
            };

            var funcError = (res) => {
                //self.init();
               // console.log("微信验证失败!!!");
            }

            wx.ready(funcSucceed);
            wx.error(funcError);            
           // GameData.MainObj.setBgMusic();//本地可以暂时取消，正式打包需要开启
           }           
    }*/

     public urlJson;
     public upload(urlStr:string,urldata:egret.URLVariables): void { 
      // console.log("发送数据到后台");
       var variables = urldata;
       var urlloader = new egret.URLLoader();
        var req = new egret.URLRequest(urlStr);
        req.method = egret.URLRequestMethod.POST;
        req.data = variables;
        urlloader.load(req);
        var self = this;
        urlloader.addEventListener(egret.Event.COMPLETE, (e) => {
            var jsObj = JSON.parse(e.target.data);
            if (jsObj) {
                self.urlJson = jsObj;
                //console.log("后台数据解析:"+JSON.stringify(self.urlJson));
                var event = new egret.Event("upload");
                self.dispatchEvent(event);
            }
        }, this);
    } 
    /****购买请求*****/
    public toShop(_timestamp:string,_nonceStr:string,_package:string,_signType:string,_paySign:string,_appId:string){
       onBridgeReady(_timestamp,_nonceStr,_package,_signType,_paySign,_appId);
       StageData.MainObj.once("PAYMENT_RETURN",(e)=>{
           //alert("购买:"+JSON.stringify(e.data));
           this.dispatchEventWith("PAYMENT_COMPLETE",false, e.data);
       },this); 
    }

    /**开始录音*/
    public startRecord(){
        wx.startRecord({}); 
        var thisObj:any = this;
        //监听录音超时
        wx.onVoiceRecordEnd({
            // 录音时间超过一分钟没有停止的时候会执行 complete 回调
            complete: function(res) {
                var localId = res.localId;
               // alert("录音本地ID:"+localId);
                this.dispatchEventWith("STOP_RECORD", false, localId);
                thisObj.uploadVoice(localId);
            }
        });
    }
    
    /**停止录音*/
    public stopRecord(){
        var thisObj:any = this;
        wx.stopRecord({
            success: function(res) {
                var localId = res.localId;  //本地录音id
                //alert("录音本地ID:"+localId);
                //thisObj.uploadVoice(localId);
                thisObj.dispatchEventWith("STOP_RECORD", false, localId);
            }
        });
    }
    public test(serveld:string){
        this.dispatchEventWith("STOP_RECORD", false, serveld);
    }
    /***上传录音 */
    
    public uploadVoice(_localld:string){
       // alert("开始上传WeixID:"+_localld);
        var thisobj = this;
        wx.uploadVoice({
        localId:_localld, // 需要上传的音频的本地ID，由stopRecord接口获得
        isShowProgressTips: 0, // 默认为1，显示进度提示
            success: function (res) {
            var serverId = res.serverId; // 返回音频的服务器端ID
            //alert("返回的服务器ID:"+serverId);
            thisobj.dispatchEventWith("UP_COMPLETE", false, serverId);
            }
        });
    }

    /**
     * 获取微信配置
     */
    private getWeiXinConfig(){
        /*
         * 注意：
         * 1. 所有的JS接口只能在公众号绑定的域名下调用，公众号开发者需要先登录微信公众平台进入“公众号设置”的“功能设置”里填写“JS接口安全域名”。
         * 2. 如果发现在 Android 不能分享自定义内容，请到官网下载最新的包覆盖安装，Android 自定义分享接口需升级至 6.0.2.58 版本及以上。
         * 3. 完整 JS-SDK 文档地址：http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html
         *
         * 如有问题请通过以下渠道反馈：
         * 邮箱地址：weixin-open@qq.com
         * 邮件主题：【微信JS-SDK反馈】具体问题
         * 邮件内容说明：用简明的语言描述问题所在，并交代清楚遇到该问题的场景，可附上截屏图片，微信团队会尽快处理你的反馈。
         */
        //配置参数
        // "&jsapi_ticket=" + jsapi_ticket+ "&nonce_str=" + nonce_str+ "&timestamp=" + timestamp+ "&signature=" + signature
        var bodyConfig = new BodyConfig();//new BodyConfig();
        bodyConfig.debug = false;// 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
        //this._dataFX = {_appid:_appid,_timestamp:_timestamp,_nonceStr:_nonceStr,_signature:_signature};
        bodyConfig.appId = this._dataFX._appid;//this.signPackage.appId;// 必填，公众号的唯一标识
        bodyConfig.timestamp = this._dataFX._timestamp;//this.signPackage.timestamp;// 必填，生成签名的时间戳
        bodyConfig.nonceStr = this._dataFX._nonceStr;//this.signPackage.nonceStr;// 必填，生成签名的随机串
        bodyConfig.signature = this._dataFX._signature;//this.signPackage.signature;// 必填，签名，见附录1
        bodyConfig.jsApiList = [// 必填，需要使用的JS接口列表，所有JS接口列表见附录2
        // 所有要调用的 API 都要加到这个列表中
            'checkJsApi',//判断当前客户端是否支持指定JS接口
            'onMenuShareTimeline',//获取“分享到朋友圈”按钮点击状态及自定义分享内容接口
            'onMenuShareAppMessage',//获取“分享给朋友”按钮点击状态及自定义分享内容接口
            'onMenuShareQQ',//获取“分享到QQ”按钮点击状态及自定义分享内容接口
            'onMenuShareWeibo',//获取“分享到腾讯微博”按钮点击状态及自定义分享内容接口
            'hideMenuItems',//批量隐藏功能按钮接口
            'showMenuItems',//批量显示功能按钮接口
            'hideAllNonBaseMenuItem',//隐藏所有非基础按钮接口
            'showAllNonBaseMenuItem',//显示所有功能按钮接口
            'translateVoice',//识别音频并返回识别结果接口        
            'startRecord',//开始录音接口
            'stopRecord',//停止录音接口
            'playVoice',//播放语音接口
            'pauseVoice',//暂停播放接口
            'stopVoice',//停止播放接口
            'uploadVoice',//上传语音接口
            'downloadVoice',//下载语音接口
            'chooseImage',//拍照或从手机相册中选图接口
            'previewImage',//预览图片接口
            'uploadImage',//上传图片接口
            'downloadImage',//下载图片接口
            'getNetworkType',//获取网络状态接口
            'openLocation',//使用微信内置地图查看位置接口
            'getLocation',//获取地理位置接口
            'hideOptionMenu',//隐藏右上角菜单接口
            'showOptionMenu',//显示右上角菜单接口
            'closeWindow',//关闭当前网页窗口接口
            'scanQRCode',//调起微信扫一扫接口
            'chooseWXPay',//发起一个微信支付请求
            'openProductSpecificView',//跳转微信商品页接口
            'addCard',//批量添加卡券接口
            'chooseCard',//调起适用于门店的卡券列表并获取用户选择列表
            'openCard'//查看微信卡包中的卡券接口
        ];
        wx.config(bodyConfig);
        //alert("分享数据设置appId:"+bodyConfig.appId);
        //alert("分享数据设置timestamp:"+bodyConfig.timestamp);
        //alert("分享数据设置nonceStr:"+bodyConfig.nonceStr);
       // alert("分享数据设置signature:"+bodyConfig.signature);        
    }

    /**
     * 获取微信分享到朋友圈
     */
    private getWeiXinShareTimeline() {
        // this.btn_sharetimeline.addEventListener(egret.TouchEvent.TOUCH_TAP, (e)=> {
        var bodyMenuShareTimeline = new BodyMenuShareTimeline();
        bodyMenuShareTimeline.title = this.title;
        bodyMenuShareTimeline.link = this.link;
        bodyMenuShareTimeline.imgUrl = this.imgUrl;
        bodyMenuShareTimeline.trigger = () => {
            // alert('用户点击分享到朋友圈');
        };
        bodyMenuShareTimeline.success = () => {
            this.getHoutai_FX();
             //alert('已分享');
            //this.thisObj.shareComplete();
            // alert("分享成功");
        };
        bodyMenuShareTimeline.cancel = () => {
            // alert('已取消');
        };
        bodyMenuShareTimeline.fail = (res) => {
             //alert(JSON.stringify(res));
        };
        wx.onMenuShareTimeline(bodyMenuShareTimeline);
        // alert('已注册获取“分享到朋友圈”状态事件');
        // }, this);
    }

    /**
     * 获取微信分享到朋友
     */
    private getWeiXinShareAppMessage() {
        // this.btn_shareappmessage.addEventListener(egret.TouchEvent.TOUCH_TAP, (e)=> {
        var bodyMenuShareAppMessage = new BodyMenuShareAppMessage();
        bodyMenuShareAppMessage.title = this.title;
        bodyMenuShareAppMessage.desc = this.desc;
        bodyMenuShareAppMessage.link = this.link;
        bodyMenuShareAppMessage.imgUrl = this.imgUrl;
        bodyMenuShareAppMessage.trigger = () => {
              //alert('用户点击发送给朋友');
        };
        bodyMenuShareAppMessage.success = () => {
            //this.thisObj.shareComplete();
            this.getHoutai_FX();
            // alert('已分享');
        };
        bodyMenuShareAppMessage.cancel = () => {
             //alert('已取消');
        };
        bodyMenuShareAppMessage.fail = (res) => {
            //alert(JSON.stringify(res));
        };
        wx.onMenuShareAppMessage(bodyMenuShareAppMessage);
        // alert('已注册获取“发送给朋友”状态事件');
        //   }, this);
    }

    /**
     * 获取微信分享到QQ
     */
    private getWeiXinShareQQ() {
        // this.btn_shareqq.addEventListener(egret.TouchEvent.TOUCH_TAP, (e)=> {
        var bodyMenuShareQQ = new BodyMenuShareQQ();
        bodyMenuShareQQ.title = this.title;
        bodyMenuShareQQ.desc = this.desc;
        bodyMenuShareQQ.link = this.link;
        bodyMenuShareQQ.imgUrl = this.imgUrl;
        bodyMenuShareQQ.trigger = () => {
            //  alert('用户点击分享到QQ');
        };
        bodyMenuShareQQ.complete = (res) => {
            //  alert(JSON.stringify(res));
        };
        bodyMenuShareQQ.success = () => {
            // alert('已分享');
           // this.thisObj.shareComplete();
        };
        bodyMenuShareQQ.cancel = () => {
            // alert('已取消');
        };
        bodyMenuShareQQ.fail = (res) => {
            // alert(JSON.stringify(res));
        };
        wx.onMenuShareQQ(bodyMenuShareQQ);
        //alert('已注册获取“分享到QQ”状态事件');
        //  }, this);
    }

    /**
     * 获取微信分享到腾讯微博
     */
    private getWeiXinShareWeiBo(){

        var bodyMenuShareWeibo = new BodyMenuShareWeibo();
        bodyMenuShareWeibo.title = this.title;
        bodyMenuShareWeibo.desc = this.desc;
        bodyMenuShareWeibo.link = this.link;
        bodyMenuShareWeibo.imgUrl = this.imgUrl;
        bodyMenuShareWeibo.trigger = () => {
            //  alert('用户点击分享到微博');
        };
        bodyMenuShareWeibo.complete = (res) => {
            // alert(JSON.stringify(res));
        };
        bodyMenuShareWeibo.success = () => {
            // alert('已分享');
            this.thisObj.shareComplete();
        };
        bodyMenuShareWeibo.cancel = () => {
            // alert('已取消');
        };
        bodyMenuShareWeibo.fail = (res) => {
            // alert(JSON.stringify(res));
        };
        wx.onMenuShareWeibo(bodyMenuShareWeibo);
        //alert('已注册获取“分享到微博”状态事件');
      
        
    }
    
    /**
    * 批量显示菜单项
    */
    private getWeixinShowMenuItems(arr_menu: any[] = null) {
        var _arr_menu: any[] = [
        //传播类
            "menuItem:share:appMessage",//发送给朋友
            "menuItem:share:timeline",//分享到朋友圈
            "menuItem:share:qq",//分享到QQ
            "menuItem:share:weiboApp",//分享到Weibo
            "menuItem:favorite",//收藏
            "menuItem:share:facebook",//分享到FB
            "menuItem:share:QZone",//分享到 QQ 空间
            
        //保护类
            "menuItem:editTag",//编辑标签
            "menuItem:delete",//删除
            "menuItem:copyUrl",//复制链接
            "menuItem:originPage",//原网页
            "menuItem:readMode",//阅读模式
            "menuItem:openWithQQBrowser",//在QQ浏览器中打开
            "menuItem:openWithSafari",//在Safari中打开
            "menuItem:share:email",//邮件
            "menuItem:share:brand" //一些特殊公众号
        ];
        if(arr_menu != null) {
            _arr_menu = arr_menu;
        };

        wx.showMenuItems({
            menuList: _arr_menu,
            success: (res) => {
                // alert('已显示“分享到朋友圈”等按钮');
            },
            fail: (res) => {
                // alert(JSON.stringify(res));
            }
        });

    }
    
    /**
    * 批量隐藏菜单项
    */
    private getWeixinHideMenuItems(arr_menu: any[] = null) {
        var _arr_menu: any[] = [
        //传播类
            "menuItem:share:appMessage",//发送给朋友
            "menuItem:share:timeline",//分享到朋友圈
            "menuItem:share:qq",//分享到QQ
            "menuItem:share:weiboApp",//分享到Weibo
            "menuItem:favorite",//收藏
            "menuItem:share:facebook",//分享到FB
            "menuItem:share:QZone",//分享到 QQ 空间
            
        //保护类
            "menuItem:editTag",//编辑标签
            "menuItem:delete",//删除
            "menuItem:copyUrl",//复制链接
            "menuItem:originPage",//原网页
            "menuItem:readMode",//阅读模式
            "menuItem:openWithQQBrowser",//在QQ浏览器中打开
            "menuItem:openWithSafari",//在Safari中打开
            "menuItem:share:email",//邮件
            "menuItem:share:brand" //一些特殊公众号
        ];
        if(arr_menu != null) {
            _arr_menu = arr_menu;
        };
        //  this.btn_hideMenuItems.addEventListener(egret.TouchEvent.TOUCH_TAP,(e) => { 
        wx.hideMenuItems({
            menuList: _arr_menu,
            success: (res) => {
                //  alert('已隐藏所有传播和保护类按钮');
            },
            fail: (res) => {
                ///  alert(JSON.stringify(res));
            }
        });
    }




    //     ----   分享统计   ----      //
    private getHoutai_FX(){
        //console.log("分享统计");
    }

    //获取地理位置接口
    //获取次数
    private locationCount:number = 0;
    public getLocation(){
        wx.getLocation({
        type: 'wgs84',
        success: function(res) {
            this.locationCount = 0;
            var latitude = res.latitude
            var longitude = res.longitude
            var speed = res.speed//速度
            var accuracy = res.accuracy//精确度
            //alert("wx:"+latitude+" ："+longitude+" : "+speed+" : "+accuracy);
            StageData.FXOBJ.dispatchEventWith("locationComplete",false,{x:latitude,y:longitude,a:accuracy});
        },
        fail:function(res){
            //alert("获取位置失败:"+JSON.stringify(res));
            if(this.locationCount<2){
                this.locationCount ++;
                this.getLocation();
            }
        }
        })
    }
   
}